#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
统计所有股票变成ST后的30天内的走势。
https://ai-cyber-security.feishu.cn/docx/PFlDduL5GoKPjwxGMIkcKmkSnBj
"""

import pandas as pd
from pathlib import Path
from datetime import datetime

debug_mode = True
#debug_mode = False
stock_code = 'sh.600107'

def analysis_stock(stock_code, data_path= 'daily_data'):
    print(f'process: {stock_code}')
    # 1. 读数据 ----------------------------------------------------------
    file_path = Path(data_path, f'{stock_code}.csv')
    if not file_path.exists():
        return None

    dtype_spec = {
        "date": "string",
        "code": "string",
        "open": pd.Float32Dtype(),    # 可空 float
        "high": pd.Float32Dtype(),
        "low": pd.Float32Dtype(),
        "close": pd.Float32Dtype(),
        "preclose": pd.Float32Dtype(),
        "volume": pd.Int64Dtype(),    # 可空 int
        "amount": pd.Float64Dtype(),
        "adjustflag": pd.Int8Dtype(),
        "turn": pd.Float32Dtype(),
        "tradestatus": pd.Int8Dtype(),
        "pctChg": pd.Float32Dtype(),
        "isST": pd.Int8Dtype()
    }

    # 读取所有股票数据，并将date列解析成datetime64[ns]，再格式为 %Y-%m-%d %H:%M:%S
    df = pd.read_csv(file_path, dtype=dtype_spec, parse_dates=["date"])#, index_col='date') 
    print('before:',type(df.date.info()))
    df.date = df.date.str.split(' ').str[0]     # 先对日期格式化成 %Y-%m-%d，然后再进行转换
    df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')#, errors='coerce')
    #df['date'] = df.date.to_pydatetime()
    df.date = df.date.map(lambda x: x.to_datetime64()) #x.strftime('%Y-%m-%d'))
    print(df.date[0], type(df.date[0]))         # 输出：2015-01-05 00:00:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'>
    print('after:',type(df.date.info()))
    df = df.set_index('date')                   # 升维成索引，后面才能按日期切
    print(df.index[0], type(df.index[0]))       # 2015-01-05 00:00:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'>

    # 选择2025/01/01的数据，若数据长度为0则返回None
    df = df[df.index >= '2025-01-01']
    if len(df) == 0:
        print(f'{stock_code} 无数据')
        return None

    size = 30
    ids = df.index.tolist()
    isSTs = df.isST.tolist()
    vs = df.close.tolist()

    res = []
    # 0=ST, 1=非ST, 2=无数据
    for i in range(len(isSTs) - 1):
        if isSTs[i] == 0 and isSTs[i+1] == 1:
            prices = [0] * size
            for j in range(0, size):
                if i + j <= len(isSTs):
                    prices[j] = vs[i+1+j]
            prices_str = [f'{p:.2f}' for p in prices]
            res = [stock_code, f'{ids[i+1]:%Y-%m-%d}'] + prices_str
            i += size
            break
    return res
    

if debug_mode:
    res = analysis_stock('sh.600107')
    print(res)
    exit() 

root = Path('daily_data').resolve()          # 支持相对/绝对路径
if not root.exists():
    raise FileNotFoundError(f'{root} 目录不存在')

print('符合,代码,ST股,最大值日期,最小值日期,下跌天数,最高价,最低价,降幅比,最低距今天数')
for csv_file in root.rglob('*.csv'):         # 递归扫描
    name_without_suffix = csv_file.stem
    abs_path = csv_file.resolve()
    try:
        res = analysis_stock(name_without_suffix)
        if res is not None and len(res) > 0:
            print(str(res)[1:-1].replace("'", ""))
    except Exception as e:
        continue
        #print(f'0, {stock_code}, {str(e)}')

print('All done.')